package com.sky.controller.admin;

import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@Api(tags = "菜品相关接口")
@RestController
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dto) {
        log.info("新增菜品：{}", dto);

        redisTemplate.delete("dish_"+dto.getCategoryId());

        dishService.addDish(dto);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result getPage(DishPageQueryDTO dto) {
        log.info("菜品分页查询：{}", dto);
        PageResult pageResult = dishService.getPage(dto);
        return Result.success(pageResult);
    }

    @ApiOperation("批量删除菜品")
    @DeleteMapping
    public Result deleteDishes(@RequestParam List<Long> ids) {
        log.info("批量删除菜品：{}", ids);

        //用*号定义通配符给到keys方法获得通配符的对象
        Set keys = redisTemplate.keys("dish_*");
        //将keys对象放入批量删除的重载方法
        redisTemplate.delete(keys);

        dishService.deleteDishs(ids);
        return Result.success();
    }

    @ApiOperation("根据id查询菜品")
    @GetMapping("/{id}")
    public Result getDishes(@PathVariable Long id) {
        log.info("根据id查询菜品：{}", id);
        DishVO vo = dishService.getDish(id);
        return Result.success(vo);
    }

    @ApiOperation("修改菜品")
    @PutMapping
    public Result updateDish(@RequestBody DishDTO dto) {
        log.info("修改菜品：{}", dto);

        //用*号定义通配符给到keys方法获得通配符的对象
        Set keys = redisTemplate.keys("dish_*");
        //将keys对象放入批量删除的重载方法
        redisTemplate.delete(keys);

        dishService.updateDish(dto);
        return Result.success();
    }

    //启售停售
    @ApiOperation("菜品起售、停售")
    @PostMapping("/status/{status}")
    public Result updateStatus(@PathVariable Integer status, Long id) {
        log.info("将菜品{}状态修改为：{}", id, status == StatusConstant.ENABLE ? "启售" : "停售");
        dishService.updateStatus(id,status);
        return Result.success();
    }

    //根据分类id查询菜品
    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result getDishesByCategoryId(Long categoryId) {
        log.info("根据分类id查询菜品：{}", categoryId);
        List<DishVO> list = dishService.getDishesByCategoryId(categoryId);
        return Result.success(list);
    }
}
